package top.ranzhang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import top.ranzhang.bean.dto.EmailOtherDTO;
import top.ranzhang.bean.dto.LoginOtherDTO;
import top.ranzhang.bean.dto.RegisterOtherDTO;
import top.ranzhang.bean.entity.other;
import top.ranzhang.bean.vo.OtherLoginVO;
import top.ranzhang.common.properties.JwtProperties;
import top.ranzhang.common.properties.MailProperties;
import top.ranzhang.constant.JwtClaimsConstant;
import top.ranzhang.exception.BaseException;
import top.ranzhang.mapper.OtherMapper;
import top.ranzhang.service.OtherService;
import top.ranzhang.utils.JwtUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@RequiredArgsConstructor
public class OtherServiceImpl extends ServiceImpl<OtherMapper, other> implements OtherService {

    private final JwtProperties jwtProperties;
    private final RedisTemplate  redisTemplate;
    private final JavaMailSender  javaMailSender;
    private final MailProperties mailProperties;

    @Override
    public OtherLoginVO loginRedis(LoginOtherDTO loginOtherDTO) {
        OtherLoginVO tep = (OtherLoginVO)redisTemplate.opsForValue().get("token:"+loginOtherDTO.getUsername());
        other one = null;
        if(tep != null){
            one = new other();
            BeanUtils.copyProperties(tep,one);
        }
        if(one == null){
            one = Db.lambdaQuery(other.class).eq(other::getUsername, loginOtherDTO.getUsername()).one();
        }
        if(one == null){
            throw new BaseException("用户不存在");
        }
        if(!one.getPassword().equals(loginOtherDTO.getPassword())){
            throw new BaseException("密码错误");
        }
        Map<String,Object> claim = new HashMap();
        claim.put(JwtClaimsConstant.OTHER_ID,one.getId());
        claim.put(JwtClaimsConstant.User_Name,one.getUsername());
        String token = JwtUtil.createJWT(jwtProperties.getOtherSecretKey(), jwtProperties.getOtherTtl(), claim);
        return OtherLoginVO.builder()
                .id(one.getId())
                .username(one.getUsername())
                .password(one.getPassword())
                .token(token)
                .build();
    }

    @Override
    public void save(RegisterOtherDTO registerOtherDTO) {
        other o = new other();
        BeanUtils.copyProperties(registerOtherDTO,o);
        o.setCreateTime(LocalDateTime.now());
        save(o);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(registerOtherDTO.getMail());
            helper.setSubject("注册成功");
            helper.setText("<h1>恭喜您，注册成功</h1>",true);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public OtherLoginVO loginEmail(EmailOtherDTO loginOtherDTO) {
        if(redisTemplate.opsForValue().get(loginOtherDTO.getEmail()).equals(loginOtherDTO.getCode())){
            other one = lambdaQuery().eq(other::getMail, loginOtherDTO.getEmail()).one();
            if(one==null){
                throw new BaseException("该邮箱未注册");
            }
            Map<String,Object> map = new HashMap<>();
            map.put(JwtClaimsConstant.OTHER_ID,one.getId());
            String token = JwtUtil.createJWT(jwtProperties.getOtherSecretKey(), jwtProperties.getOtherTtl(), map);
            return OtherLoginVO.builder()
                    .id(1)
                    .username(one.getUsername())
                    .password("****")
                    .token(token)
                    .build();
        }else{
            throw new BaseException("验证码错误");
        }
    }

    @Override
    public void getEmailCode(String email) {
        Random random = new Random();
        String code = "";
        for(int i = 0; i < 4; i++){
            code += random.nextInt(10);
        }
        log.info("验证码：{}",code);
        redisTemplate.opsForValue().set(email,code);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom("2426431465@qq.com");
            helper.setTo(email);
            helper.setSubject("登录验证码");
            helper.setText("<h1>"+ code +"</h1>",true);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
